//HC_SR04.c
#include "regx52.h"
#include "Delay.h"
#include "HC_SR04.h"


sbit SR_TR = P2^1;
sbit SR_EC = P2^0;

unsigned int HC_SR04_Value = 0;

void HC_SR04_Init()    //推荐检测周期为60ms以上
{
	T2MOD = 0;		//初始化模式寄存器
	T2CON = 0;		//初始化控制寄存器
	TL2 = 0xA0;		//设置定时初值
	TH2 = 0x15;		//设置定时初值
	RCAP2L = 0xA0;		//设置定时重载值
	RCAP2H = 0x15;		//设置定时重载值
	TR2 = 1;		//定时器2开始计时
	ET2 = 1;
	EA  = 1;
	PT2 = 1;
	TF2 = 0;
	
	HC_SR04_RxTim_Init();
	SR_EC = 1;
}

void HC_SR04_RxTim_Init()
{
	TMOD &= 0xF0;		//设置定时器模式
	TMOD |= 0x01;		//设置定时器模式
	TL0 = 0x00;		//设置定时初值
	TH0 = 0x00;		//设置定时初值
	TF0 = 0;		//清除TF0标志
	TR0 = 1;		//定时器0开始计时
}

void HC_SR_Run_Rountine()	interrupt 5
{
	SR_EC = 0;
	
	SR_TR = 1;		//开始脉冲
	Delayus(10);
	SR_TR = 0;
	
	while(!SR_EC);
	TR0 = 1;			//定时器0开始计时
	while(SR_EC);
	TR0 = 0;			//定时器0结束计时
	
	HC_SR04_Value = (TH0*256+TL0); //计算回波时长，距离 = 采集到的时间*声速（340M/S）/2；
	
	TH0 = 0;
	TL0 = 0;
	TF2 = 0;
}
